package com.spm.librarianmanagersystem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.mapper.BookBookIdMapper;
import com.spm.librarianmanagersystem.mapper.BookMapper;
import com.spm.librarianmanagersystem.mapper.BorrowMapper;
import com.spm.librarianmanagersystem.pojo.Book;
import com.spm.librarianmanagersystem.service.BookCopyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("BookCopyService")
public class BookCopyServiceImpl implements BookCopyService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    BookBookIdMapper bbim;

    @Override
    @Transactional
    public String deleteCollection(String isbn, Integer bookId) throws Exception {
        // 检查指定的副本是否存在
        Book book = bookMapper.getBookById(isbn, bookId);
        if (book == null) {
            throw new Exception("指定的图书不存在, 删除失败");
        }
        // 检查指定的副本是否被借出
        Integer count = borrowMapper.getUnreturnedCountByBookId(isbn, bookId);
        if (count > 0) {
            throw new Exception("指定的图书已被借出, 删除失败");
        }

        // 删除指定副本
        Boolean ok = bookMapper.deleteBookById(isbn, bookId);
        if (ok == null || !ok) {
            throw new Exception("删除副本时出错");
        }
        return "删除成功";
    }

    @Override
    public Boolean editStatus(JSONObject obj) {
        String ISBN = obj.getString("ISBN");
        Integer bookId = obj.getInteger("book_id");
        Integer status = obj.getInteger("status");
        return bbim.editStatus(ISBN, bookId, status);
    }
}
